package awt.awt05;

import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;

public class imageIO {
    private Frame fr=new Frame("图片查看器");

    MenuBar menuBar=new MenuBar();
    Menu menu=new Menu("文件");
    MenuItem open=new MenuItem("打开");
    MenuItem save=new MenuItem("另存为");

    BufferedImage image;

    private class MyCanvas extends Canvas{
        @Override
        public void paint(Graphics g){
            g.drawImage(image,0,0,null);
        }
    }

    MyCanvas drawArea = new MyCanvas();


    public void init(){


        // 打开图片

        open.addActionListener(e->{
            FileDialog fileDialog=new FileDialog(fr,"打开图片",FileDialog.LOAD);
            fileDialog.setVisible(true);

            // 获取用户选择图片路径以及名称
            String dir=fileDialog.getDirectory();
            String fileName=fileDialog.getFile();

            System.out.println(dir);
            System.out.println(fileName);

            try {
                image= ImageIO.read(new File(dir,fileName));
                drawArea.repaint();
                System.out.println(image);
            } catch (IOException ex) {
                ex.printStackTrace();
            }

        });

        //保存图片
        save.addActionListener(e->{
            FileDialog fileDialog=new FileDialog(fr,"保存图片",FileDialog.SAVE);
            fileDialog.setVisible(true);

            //获取用户设置保存路径以及文件名称
            String dir=fileDialog.getDirectory();
            String fileName=fileDialog.getFile();
            try {
                ImageIO.write(image,"JPEG",new File(dir,fileName));
            } catch (IOException ex) {
                ex.printStackTrace();
            }
        });

        menu.add(open);
        menu.add(save);
        menuBar.add(menu);

        fr.setMenuBar(menuBar);
        fr.add(drawArea);

        fr.setBounds(200,200,740,508);
        fr.setVisible(true);

        fr.addWindowListener(new WindowAdapter(){
           @Override
           public void windowClosing(WindowEvent e){
               System.exit(0);
           }
        });
    }

    public static void main(String[] args) {
        new imageIO().init();
    }
}
